<?php
declare (strict_types = 1);

namespace app\common\server;
use app\api\controller\Base;
use app\common\model\Infinite;
use app\common\model\InfiniteList;
use app\common\model\InfiniteOrder;
use app\common\model\InfiniteOrderList;
use app\common\model\InfiniteOrderListInfo;
use app\common\model\User;
use app\common\model\ClimbUser;
use app\common\model\ClimbRankUser;
use app\common\server\RedisLock as Lock;
use \think\Request;

class ClimbOpenBox extends Base
{
    /**
     * 盲盒开奖品
     */
    public function open_box($order_id){
        $order = InfiniteOrder::getInfo(['id'=>$order_id],'id,order_num,user_id,goods_id,buy_num,barrier_num');
        $w = [];
        $w[] = ['infinite_id','=',$order['goods_id']];
        $w[] = ['status','=','1'];
        $w[] = ['goods_type','<>','2'];		//排除任意门商品
        $w[] = ['goods_type','<>','3'];		//排除任意门商品
        $w[] = ['goods_type','<>','4'];		//排除任意门商品
        $w[] = ['barrier_num','=',$order['barrier_num']];
        $w[] = ['barrier_type','<','4'];		//排除任意门商品
        $field="id,title,imgurl,price,money,gailv,stock,shang_id,goods_type,yunfei,climb_key,climb_stone,is_tui";
        $goodslist = InfiniteList::getAllList($w,$field,'stock desc');
        $total_stock = InfiniteList::where($w)->sum('stock');			//总库存
        $buy_num = $order['buy_num'];
        //获取奖池
        $num = 0;
        $tempdata = array ();
        $goodslist = $goodslist->toArray();
        if(empty($goodslist)){
            return 2;
        }
        $yu = $total_stock-$buy_num;
        foreach ($goodslist as $one) {
            if($yu < 20){
                $w = [];
                $w[] = ['status','=','1'];
                $w[] = ['id','=',$one['id']];
                $w[] = ['barrier_num','=',$order['barrier_num']];
                InfiniteList::where($w)->inc('stock', (int)$one['gailv'])->update();
            }
            if($one['stock'] < 1){
                continue;
            }
            $num += $one['stock'];
            for ($i = 0; $i < $one['stock']; $i++) {
                $tempdata[] = $one;
            }
        }
        $tempdata = shuffle_assoc($tempdata);

        $zhong = [];
        if($buy_num == 1){
            //开奖
            $use = rand(0, $num-1);
            $one = $tempdata[$use];
            $zhong = [$one];
        }elseif($buy_num > 1){
            $rand_array=range(0,$num-1);
            shuffle($rand_array);  //调用现成的数组随机排列函数
            $res = array_slice($rand_array,0,$buy_num); //截取前$limit个
            for($i=0;$i<$buy_num;$i++){
                $zhong[$i] = $tempdata[$res[$i]];
            }
        }
        $order_num = $order['order_num'];
        $arr = $goodslist_id = $row = [];
        $time = time();
        $total_climb_key = $total_climb_stone = 0;
        $total_price = 0;
        foreach($zhong as $k=>$v){
            $total_price += $v['price'];
            //订单记录
            $arr[$k]['user_id'] = $order['user_id'];
            $arr[$k]['order_num'] = $order_num;
            $arr[$k]['order_id'] = $order_id;
            $arr[$k]['goods_id'] = $order['goods_id'];
            $arr[$k]['goodslist_id'] = $v['id'];
            $arr[$k]['imgurl'] = $v['imgurl'];
            $arr[$k]['price'] = $v['price'];
            $arr[$k]['out_money'] = $v['money'];	//回收价格
            $arr[$k]['title'] = $v['title'];
            $arr[$k]['shang_id'] = $v['shang_id'];
            $arr[$k]['yunfei'] = $v['yunfei'];
            $arr[$k]['is_tui'] = $v['is_tui'];
            $arr[$k]['status'] = 1;
            $arr[$k]['order_from'] = 1;
            $arr[$k]['addtime'] = $time;
            $arr[$k]['goods_from'] = 1;
            $arr[$k]['barrier_num'] = $order['barrier_num'];
            $goodslist_id[$k] = $v['id'];
            //奖品信息
            $row[$k]['user_id'] = $order['user_id'];
            $row[$k]['order_id'] = $order_id;
            $row[$k]['goods_id'] = $order['goods_id'];
            $row[$k]['goodslist_id'] = $v['id'];
            $row[$k]['title'] = $v['title'];
            $row[$k]['imgurl'] = $v['imgurl'];
            $row[$k]['shang_id'] = $v['shang_id'];
            $row[$k]['goods_type'] = $v['goods_type'];
            $row[$k]['is_tui'] = $v['is_tui'];
            $row[$k]['addtime'] = $time;
            $row[$k]['order_from'] = 1;
            $row[$k]['barrier_num'] = $order['barrier_num'];
            $total_climb_key += $v['climb_key'];
            $total_climb_stone += $v['climb_stone'];
        }
        $my_res = array_count_values($goodslist_id);
        foreach($my_res as $k=>$v){
            $ss = InfiniteList::where(['id'=>$k])->dec('stock',$v)->update();
        }

        Infinite::where(['id'=>$order['goods_id']])->inc('sale_num',$buy_num)->update();
        $dd = (new InfiniteOrderList)->saveAll($arr);
        $ss = (new InfiniteOrderListInfo)->saveAll($row);
        if($total_climb_key > 0){
            User::changeClimbKey($order['user_id'],$total_climb_key,2);
        }
        if($total_climb_stone > 0){
            User::changeClimbStone($order['user_id'],$total_climb_stone,2);
        }
        //计入盈亏
        User::where(['id'=> $order['user_id']])->dec('loss_total', $total_price)->update();

        $ff = self::barrier_sheng($order['goods_id'],$my_res,$order['user_id'],$order['barrier_num'],$order['id']);//判断是否需要晋级
        return 1;
    }

    /**
     * 通关奖励
     */
    public static function through_barrier($user_id,$goods_id,$order_id,$barrier_num){
        //判断是否是首次通过
        $ww = [];
        $ww[] = ['user_id','=',$user_id];
        $ww[] = ['infinite_id','=',$goods_id];
        $ww[] = ['barrier_num','=',$barrier_num];
        $res = ClimbUser::getInfo($ww,'id,user_id,barrier_num');
        if(empty($res)){
            return 44;
        }
        $w = [];
        $w[] = ['id','=',$goods_id];
        $w[] = ['type','=','7'];
        $infinite = Infinite::getinfo($w,'id,headimg,head_title');
        if(empty($infinite)){
            return 3;
        }
        //查询奖品信息
        $ww= [];
        $ww[] = ['infinite_id','=',$goods_id];
        $ww[] = ['barrier_num','=',$barrier_num];
        $ww[] = ['barrier_type','=',4];
        $field="id,title,imgurl,price,money,gailv,stock,shang_id,goods_type,barrier_num,is_tui";
        $goods_list = InfiniteList::getInfo($ww,$field);
        if(empty($goods_list)){
            return 4;
        }
        $arr = $row = [];
        $time = time();

        //订单记录
        $arr['user_id'] = $user_id;
        $arr['order_num'] = $order_id;
        $arr['order_id'] = '-8';
        $arr['goods_id'] = $goods_id;
        $arr['goodslist_id'] = $goods_list['id'];
        $arr['imgurl'] = $goods_list['imgurl'];
        $arr['price'] = $goods_list['price'];
        $arr['out_money'] = $goods_list['money'];	//回收价格
        $arr['title'] = $goods_list['title'];
        $arr['shang_id'] = $goods_list['shang_id'];
        $arr['is_tui'] = $goods_list['is_tui'];
        $arr['status'] = 1;
        $arr['order_from'] = 7;
        $arr['addtime'] = $time;
        $arr['goods_from'] = 1;
        $arr['barrier_num'] = $goods_list['barrier_num'];
        //奖品信息
        $row['user_id'] = $user_id;
        $row['order_id'] = "-8";
        $row['goods_id'] = $goods_id;
        $row['goodslist_id'] = $goods_list['id'];
        $row['title'] = $goods_list['title'];
        $row['imgurl'] = $goods_list['imgurl'];
        $row['shang_id'] = $goods_list['shang_id'];
        $row['is_tui'] = $goods_list['is_tui'];
        $row['goods_type'] = $goods_list['goods_type'];
        $row['addtime'] = $time;
        $row['order_from'] = 7;
        $row['barrier_num'] = $goods_list['barrier_num'];

        $dd = (new InfiniteOrderList)->insert($arr);
        $ss = (new InfiniteOrderListInfo)->insert($row);
        if($ss && $dd){
            return 1;
        }else{
            return 2;
        }
    }

    /**
     * 闯关升级降级
     */
    public static function barrier_sheng($goods_id,$goodslist_id = array(),$user_id,$barrier_num,$order_id)
    {
        $goodslist_ids = array_keys($goodslist_id);
        //判定该商品是否是可以晋级
        $w = [];
        $w[] = ['infinite_id','=',$goods_id];
        $w[] = ['barrier_type','=',2];//晋级
        $w[] = ['barrier_num','=',$barrier_num];
        $w[] = ['status','=',1];
        $goodslist = InfiniteList::getInfo($w,'id,barrier_type,barrier_num');
        $is_barrier = 1;
        if(in_array($goodslist['id'],$goodslist_ids)){
            //添加升级记录
            $is_barrier = 2;
            $goodslist_id_two = $goodslist['id'];
        }
        //判定该商品是否是可以降级
        $w = [];
        $w[] = ['infinite_id','=',$goods_id];
        $w[] = ['barrier_type','=',3]; //3=降级奖品
        $w[] = ['barrier_num','=',$barrier_num];
        $w[] = ['status','=',1];
        $goodslist = InfiniteList::getInfo($w,'id,barrier_type,barrier_num');
        if(in_array($goodslist['id'],$goodslist_ids)){
            //添加降级记录
            if($is_barrier==1){
                $is_barrier = 3;
                $goodslist_id_two = $goodslist['id'];
            }else{
                $is_barrier = 4;
            }
        }
        $ww = [];
        $ww[] = ['user_id','=',$user_id];
        $ww[] = ['goods_id','=',$goods_id];
        $barrier = 1;

        if($is_barrier == 2){ //升级
            $ss = self::through_barrier($user_id,$goods_id,$order_id,$barrier_num);
            if($barrier_num < 9){
                $barrier_num++;
            }else{
                $barrier_num = 1;
                self::ding_add($user_id,$goods_id);
            }
            //升级
            $arr = [];
            $arr['user_id'] = $user_id;
            $arr['infinite_id'] = $goods_id;
            $arr['order_id'] = $order_id;
            $arr['goodslist_id'] = $goodslist_id_two;
            $arr['barrier_num'] = $barrier_num;
            $arr['day'] = date("Y-m-d");
            $arr['addtime'] = time();
            $dd = ClimbUser::insert($arr);
            if($dd){
                return 1;
            }else{
                return 2;
            }
        }elseif($is_barrier == 3){	//降级
            if($barrier_num < 2){
                $barrier_num = 1;
            }else{
                $barrier_num--;
            }
            $arr = [];
            $arr['user_id'] = $user_id;
            $arr['infinite_id'] = $goods_id;
            $arr['order_id'] = $order_id;
            $arr['goodslist_id'] = $goodslist_id_two;
            $arr['barrier_num'] = $barrier_num;
            $arr['day'] = date("Y-m-d");
            $arr['addtime'] = time();
            $dd = ClimbUser::insert($arr);
            if($dd){
                return 1;
            }else{
                return 2;
            }
        }
    }

    /**
     * 通关添加登顶次数
     */
    public static function ding_add($user_id,$goods_id){
        $ww = [];
        $ww[] = ['user_id','=',$user_id];
        $ww[] = ['infinite_id','=',$goods_id];
        $res = ClimbRankUser::getInfo($ww,'*');
        if(empty($res)){
            $arr = [];
            $arr['user_id'] = $user_id;
            $arr['infinite_id'] = $goods_id;
            $arr['number'] = 1;
            $arr['end_time'] = time();
            $dd = ClimbRankUser::insert($arr);
            return 1;
        }else{
            $row = [];
            $row['end_time'] = time();
            $w = [];
            $w[] = ['id','=',$res['id']];
            $dd = ClimbRankUser::where($w)->inc('number')->update($row);
            return 1;
        }
    }
}